<template>
	<eui-background type="common">
		<eui-nav-bar title="订单详情" color="#fff" rightIcon="">
			<template v-slot:right="">
				<view @click="confirmAudit">稽核</view>
			</template>
		</eui-nav-bar>
		<view class="footer" :style="{ height: height + 'px', 'overflow-y': 'scroll' }">
			<scroll-view scroll-y="true" style="height: 100%;">
				<mCard :title="false" :type="true" v-show="true">
					<template v-slot:content="">
						<view class="flex align-center"
							style="min-height: 60px;padding: 4px;margin-bottom: 8px;font-size: 32rpx;">
							<view style="width: 30%;text-align: center;font-weight: bold;">{{
								getBcmDictName('orderStatus', bcmOrder.orderStatus) }}</view>
							<view style="flex: 1;">
								<view class="flex just-between">
									<view class="flex just-between align-center">
										<view
											:style="{ background: getBcmDictItem('chnlType', bcmOrder.chnlType).color }"
											class="chnltype">
											{{ getBcmDictItem('chnlType', bcmOrder.chnlType).text }}
										</view>
										<view v-if="bcmOrder.thirdOrderIndex"
											style="font-size: 42rpx;font-weight: bold;">#<text>{{
												bcmOrder.thirdOrderIndex }}</text>
										</view>
									</view>
									<view
										style="width:70rpx;height: 70rpx;border-radius: 70rpx;background:#EDEDED;margin-right: 30rpx;"
										class="flex align-center just-center" @click.stop="setPrint">
										<image :src="_img_printer" style="height: 35rpx;width: 35rpx;"></image>
									</view>
								</view>
								<view style="font-size: 28rpx;margin-top: 10rpx;" v-if="bcmOrder.pickType != '2'">
									预计{{ bcmOrder.pickType == '0' ? '送达' : '自提' }}<text style="margin-left: 8px;">{{
										bcmOrder.expectDeliveryTime }}前</text>
								</view>
							</view>
						</view>
					</template>
				</mCard>
				<mCard :title="true" templateTitle="物流信息" :type="true" v-show="deliverList?.length > 0">
					<template v-slot:content="">
						<uni-steps :options="deliverList" active-color="#007AFF" direction="column" />
					</template>
				</mCard>
				<mCard :title="true" templateTitle="基本信息" :type="true">
					<template v-slot:content="">
						<view class="m-list-top">
							<eui-text v-model="bcmOrder.thirdOrderNo" title="订单号：" type="name" occupy class="ht-30" />
							<eui-text v-model="bcmOrder.storeName" title="门店：" type="name" class="ht-30" />
							<eui-text v-model="bcmOrder.logisticsCode"
								:name="getBcmDictName('logisticsCode', bcmOrder.logisticsCode)" type="titlename"
								title="配送方:" v-if="getBcmDictName('logisticsCode', bcmOrder.logisticsCode)"
								class="ht-30" />
							<eui-text v-model="bcmOrder.buyerRemark" title="备注：" type="name" v-if="bcmOrder.buyerRemark"
								occupy class="ht-30" />
						</view>
					</template>
				</mCard>
				<mCard :title="true" templateTitle="商品信息" :type="true">
					<template v-slot:content="">
						<goods-list :goods-list="bcmOrder.bcmOrderGoodsList"></goods-list>
						<view style="padding: 0 15rpx 15rpx 0;">
							<order-state :scope="bcmOrder" />
							<view v-if="!!bcmOrderPayList.length"
								style="border-top: 1rpx dashed #E1E1E1;margin-top: 6rpx;padding: 3rpx 0;">
								<view v-for="(f, i) in bcmOrderPayList" :key="i">
									<view class="flex just-between"
										style="line-height:42rpx;font-size: 32rpx;padding: 10rpx 0 0;">
										<view class="">
											{{ f.payName }}
										</view>
										<view class="" style="color: #E43E00;text-align: right;font-weight: bold;">
											{{ formatPrice(f.amount) }}
										</view>
									</view>
								</view>
							</view>
							<view class="flex just-between" style="font-size: 32rpx;" v-else>
								<view>
									顾客实付
								</view>
								<view class="" style="color: #E43E00;text-align: right;font-weight: bold;">
									{{ formatPrice(bcmOrder.totalAmount) }}
								</view>
							</view>
						</view>
					</template>
				</mCard>

				<mCard :title="true" templateTitle="退款信息"
					v-show="bcmOrder?.orderStatus != '8' && !!bcmAfsOrderList && bcmAfsOrderList?.length">
					<template v-slot:content="">
						<view v-for="(a, index) in bcmAfsOrderList" :key="index">
							<view style="border-bottom: 1px solid #fafafa;">
								<view class="font-13" style="padding: 8px 4px">
									<view class="flex ht-30">
										<view class="co-9e" style="margin-right: 15px;">发起时间</view>
										<view>{{ a.sponsorTime }}</view>
									</view>
									<view class="flex ht-30">
										<view class="co-9e" style="margin-right: 15px;">退款数量</view>
										<view>{{ a.afsOrderGoodsNum }}</view>
									</view>
									<view class="flex ht-30">
										<view class="co-9e" style="margin-right: 15px;">退款金额</view>
										<view>{{ formatPrice(a.refundAmount) }}</view>
									</view>
									<view class="flex">
										<view class="co-9e" style="margin-right: 15px;">退款原因</view>
										<view class="flex-1">{{ a.afsReason }}</view>
									</view>
									<view class="co-9e font-13">退款商品</view>
									<goods-list :goods-list="a.bcmAfsOrderGoodsList" type="afs"></goods-list>
									<view style="padding: 0 15rpx 15rpx 0;">
										<afs-order-state :a="a" :scope="bcmOrder" />
									</view>
								</view>
							</view>
						</view>
					</template>
				</mCard>
				<mCard :title="true" templateTitle="用户信息">
					<template v-slot:content="">
						<view style="padding: 8px 4px;font-size: 32rpx;">
							<view class="flex ht-30">
								<view class="co-9e" style="margin-right: 15px;">下单时间</view>
								<view>{{ bcmOrder.orderCreateTime }}</view>
							</view>
							<view class="flex ht-30">
								<view class="co-9e" style="margin-right: 15px;">顾客姓名</view>
								<view>{{ bcmOrder.consigneeName }}</view>
							</view>
							<view class="flex ht-30">
								<view class="co-9e" style="margin-right: 15px;">顾客电话</view>
								<view>{{ bcmOrder.consigneePhone }}</view>
							</view>
							<view class="flex">
								<view class="co-9e" style="margin-right: 15px;">顾客地址</view>
								<view class="flex-1">{{ bcmOrder.consigneeAddress }}</view>
							</view>
						</view>
					</template>
				</mCard>
			</scroll-view>
		</view>
		<view class="bottom" v-if="bcmOrder?.orderStatus">
			<OrderOperateBtn :scope="bcmOrder" @close="close" @fetchData="billQuery" v-model:currentItem="bcmOrder"
				v-model="bcmOrder" v-model:showOrderPickupPop="showOrderPickupPop" v-model:modalType="modalType"
				v-model:showCancelOrderPopup="showCancelOrderPopup" v-model:isOrderCancel="isOrderCancel"
				v-model:title="title" v-model:showDeliveryCancelPopup="showDeliveryCancelPopup"
				v-model:dealType="dealType" v-model:dealList="dealList" @orderItemPrint="setPrint"
				v-model:billType="billType" :showConfigModal="showConfigModal" />
		</view>
		<!-- 拣货弹窗 -->
		<OrderPickPopup :show="showOrderPickupPop" :scope="bcmOrder" @close="showOrderPickupPop = false"
			@orderAction="orderAction" />
		<!-- 取消配送弹窗 -->
		<DeliveryCancelPopup :show="showDeliveryCancelPopup" @close="close" :scope="bcmOrder"
			@select="selectDeliveryCancelItem" @inputchange="inputDeliveryChange" :billType="billType">
			<template v-slot="">
				<view class="bottom-1">
					<eui-button type="primary" title="确认" style="width: 50%;" singleTag="deliveryCancelSure"
						@click="deliveryCancelSure" />
				</view>
			</template>
		</DeliveryCancelPopup>
		<!-- 取消订单、拒单、驳回入库申请弹窗 -->
		<CancelOrderPopup :show="showCancelOrderPopup" @close="close" :scope="bcmOrder" :title="title"
			:modalType="modalType" :dealList="dealList" :orderCancelReasonType="orderCancelReasonType"
			@select="selectItem" @inputchange="inputChange">
			<template v-slot="">
				<view class="bottom-1">
					<eui-button type="primary" title="确认" style="width: 50%;"
						@click="orderSureCancel(bcmOrder, modalType, isOrderCancel, dealType, orderCancelReasonType, rejectReason, orderAction, showConfigModal)" />
				</view>
			</template>
		</CancelOrderPopup>
	</eui-background>
</template>
<script setup lang="js">
import { mapState, mapMutations } from 'vuex';
import { ref, onUnmounted, onMounted } from 'vue'
import { storeToRefs } from "pinia";
import { onLoad, onShow } from "@dcloudio/uni-app";
import service from '../../../common/service';
import { bcmRequest, getBcmUrl } from '../../../hooks/bcmServices';
import { getBcmDictList, getBcmDictName, getBcmDictItem, formatPrice } from '../../../hooks/bcmUseUntils';
// import { handleBLEdevicess } from '../utils/PrintFormatUtil.js'
import BluetoothPrinter from '@/common/BluetoothPrinter';
import { useMainStore } from "@/store/modules/store";
import { usePrinterStore } from "@/store/printerStore";
import { usePrintTaskStore } from "@/store/usePrintTaskStore";
import GoodsList from '../components/GoodsList.vue'
import OrderState from './components/OrderState.vue'
import AfsOrderState from './components/AfsOrderState.vue'
import OrderOperateBtn from './components/OrderOperateBtn.vue';
import OrderPickPopup from './components/OrderPickPopup.vue'
import DeliveryCancelPopup from './components/DeliveryCancelPopup.vue'
import CancelOrderPopup from './components/CancelOrderPopup.vue'
import { orderSureCancel } from './utils/cancelOrder.js'
import { getPrintData } from '../utils/PrintFormatUtil.js'
import mCard from '../components/Card.vue'
import uniSteps from '../components/Steps.vue'
import _img_printer from '../../../static/img/bcmIcons/printer.png'

const bcmUrl = getBcmUrl()

const height = ref(0)
const BillId = ref('');
const bcmOrder = ref(null);
const deliverList = ref([])
const bcmAfsOrderList = ref([])
const bcmOrderPayList = ref([])

const showDeliveryCancelPopup = ref(false)
const showOrderPickupPop = ref(false)
const isOrderCancel = ref(false)
const showCancelOrderPopup = ref(false)
const rejectReason = ref('')
const orderDeliveryCancelReasonType = ref({})
const orderDeliveryCancelReason = ref('')
const orderCancelReasonType = ref('')
const modalType = ref('cancel')
const title = ref('取消订单原因')
const dealType = ref('3')
const dealList = ref([])

const isPrinting = ref(false)
const isSkip = ref(false)
const showConfigModal = ref(false)
const billType = ref('1')

const mainStore = useMainStore();
const printerStore = usePrinterStore();
const { addTask } = usePrintTaskStore();
const { printTimes, bluetoothPrinter } = storeToRefs(printerStore);

const selectItem = function (item) {
	orderCancelReasonType.value = item.detail.value;
}

const selectDeliveryCancelItem = function (item) {
	orderDeliveryCancelReasonType.value = item;
}

const inputChange = function (e) {
	rejectReason.value = e.detail.value;
}

const inputDeliveryChange = function (e) {
	orderDeliveryCancelReason.value = e.detail.value;
}

const deliveryCancelSure = () => {
	orderAction({
		uniqueKey: '订单表',
		methodName: 'CancelDelivery'
	}, bcmOrder.value, {
		orderDeliveryCancelReason: orderDeliveryCancelReasonType.value?.mustInputFlag == '1' ? orderDeliveryCancelReason.value : orderDeliveryCancelReasonType.value?.name,
		orderDeliveryCancelReasonType: orderDeliveryCancelReasonType.value?.code
	}, '取消配送操作成功', true);
}

const confirmAudit = () => {
	uni.showModal({
		title: '稽核订单',
		content: '此操作会获取第三方平台最新订单状态并同步到中台系统，您确定要“稽核订单”吗？',
		showCancel: true,
		success: (res) => {
			if (res.confirm) {
				orderAction({
					uniqueKey: '订单表',
					methodName: 'auditOrder'
				}, bcmOrder.value, undefined, '订单稽核成功');
			} else { }
		}
	});
}

const addPrintTaskFn = function (v, type = 'order', isAutoPrint = false) {
	addTask({
		id: type == 'order' ? v.orderNo : v.afsOrderNo,
		task: async () => await handleTaskPrint(v, type, isAutoPrint)
	})
}

const handleTaskPrint = function (order, type, isAutoPrint = false) {
	return new Promise((resolve) => {
		let data = getPrintData(order, type, printTimes.value), skip = isAutoPrint ? '0' : (isSkip.value ? '1' : '0');
		BluetoothPrinter.setDevice(bluetoothPrinter.value).checkAndPrint(data).then((res) => {
			if (res.code == '0') {
				if (type == 'afs') {
					ConfirmAfsOrderPrint(order, skip)
				} else {
					ConfirmOrderPrint(order, skip)
				}
			}
			resolve()
		}).catch(res => {
			if (!isAutoPrint) {
				skipFunc(res?.msg);
			}
		})
	})
}

const skipFunc = function (contenet = '打印失败，是否跳过打印流程进行后续操作？') {
	uni.showModal({
		title: '提示',
		content: contenet,
		showCancel: true,
		mask: true,
		success: (res) => {
			if (res.confirm) {
				isSkip.value = true;
				isPrinting.value = false;
				// resolve()
				ConfirmOrderPrint(bcmOrder.value, '1')
			} else {
				skipReset()
			}
		}
	})
}

const setPrint = function (v, type = 'order', isAutoPrint = false) {
	return new Promise((resolve, reject) => {
		if (mainStore.enjoyServiceIp && mainStore.enjoyServiceIp.EnjoyBCM) {
			if (!isAutoPrint) {
				if (!bluetoothPrinter.value?.deviceId) {
					skipFunc("未设置蓝牙打印机，是否跳过打印？")
					return;
				}
				addPrintTaskFn(bcmOrder.value, type, isAutoPrint)
			} else {
				console.log("当前未设置蓝牙打印机");
				// skipFunc("当前未设置蓝牙打印机，是否跳过打印？")
			}
		}
	})
}

const skipReset = () => {
	isPrinting.value = false;
	isSkip.value = false;
}

const ConfirmAfsOrderPrint = (v, skipPrintFlag = '0') => {
	orderAction({
		uniqueKey: '售后单表',
		methodName: 'ConfirmAfsOrderPrint'
	}, v, {
		afsOrderNo: v.afsOrderNo,
		afsOrderId: v.afsOrderId,
		BillId: v.afsOrderId,
		thirdAfsOrderNo: v.thirdAfsOrderNo,
		extras: {
			operateMode: '手动',
			operateTerminal: 'APP',
			skipPrintFlag
		}
	})
}

const ConfirmOrderPrint = (v, skipPrintFlag = '0') => {
	orderAction({
		uniqueKey: '订单表',
		methodName: 'confirmOrderPrint'
	}, v, {
		operateMode: '手动',
		operateTerminal: 'APP',
		skipPrintFlag
	})
}


const confirmPrint = function () {
	// if (!isPrinting.value) {
	// 	isPrinting.value = true;
	// 	service.enjoyShowLoading("打印中...");
	// 	handleBLEdevicess({
	// 		v: bcmOrder.value,
	// 		type: 'order',
	// 		reset: {
	// 			skip,
	// 			skipCancel
	// 		}
	// 	}).then(() => {
	// 		orderAction({
	// 			uniqueKey: '订单表',
	// 			methodName: 'confirmOrderPrint'
	// 		}, bcmOrder.value, {
	// 			operateMode: '手动',
	// 			operateTerminal: 'APP',
	// 			skipPrintFlag: isSkip.value ? '1' : '0'
	// 		})
	// 	}).finally(() => {
	// 		console.log("confirmPrint, isPrinting", isPrinting.value)
	// 		service.enjoyHideLoading();
	// 		skipCancel()
	// 	})
	// } else {
	// 	console.log('正在打印中')
	// }
}

const close = () => {
	showCancelOrderPopup.value = false;
	showCancelOrderPopup.value = false;
	showOrderPickupPop.value = false;
	modalType.value = 'cancel';
	title.value = '取消订单原因';
	orderCancelReasonType.value = '';
	orderDeliveryCancelReason.value = '';
	orderDeliveryCancelReasonType.value = {};
	rejectReason.value = '';
	isOrderCancel.value = false;
}

onMounted(() => {
	uni.getSystemInfo({
		success: function (res) { // res - 各种参数 
			let info = uni.createSelectorQuery().select(".navigation");
			info.boundingClientRect(function (data) { //data - 各种参数
				// height.value = res.windowHeight - data.height;
			}).exec()
		}
	});
})

const orderAction = async function ({
	uniqueKey,
	methodName
}, v, params = undefined, text = '', popup = false, fn = undefined) {
	service.enjoyShowLoading('正在加载...');
	let param = {
		chnlCode: v.chnlCode,
		chnlType: v.chnlType,
		orderNo: v.orderNo,
		storeCode: v.storeCode,
		thirdOrderNo: v.thirdOrderNo,
		orderId: v.orderId,
		...params,
	}
	const response = await bcmRequest(bcmUrl.orderApi, uniqueKey, methodName, param);
	service.enjoyHideLoading();
	if (text) {
		uni.showToast({
			title: text,
			icon: 'none'
		});
	}
	if (popup) {
		close()
	}
	await billQuery();
	if (fn) {
		fn(v)
	}
	if (params) {
		return response
	}
}

onShow(() => {
	uni.setStorageSync('ispreviewImage', false)
})

onUnmounted(() => {
	uni.$off('REFRESH_ORDER_DETAIL_DATA')
})

const billQuery = async (id = BillId.value) => {
	bcmOrder.value = {}
	service.enjoyShowLoading('正在加载...');
	const req = {
		BillId: id,
		extras: {
			queryAfsOrder: "1",
			queryAfsApproved: "1"
		}
	};
	const result = await bcmRequest(bcmUrl.orderApi, '订单表', 'EnjoyBillQuery', req);
	service.enjoyHideLoading();
	if (!!result.ds.bcmOrder) {
		bcmOrder.value = result.ds.bcmOrder;
		if (result.ds1.length > 0) {
			deliverList.value = result.ds1.sort((a, b) => new Date(b.operateTime.replace(/-/g, "/")).getTime() - new Date(a
				.operateTime.replace(/-/g, "/")).getTime()).map(v => {
					v.title = v.deliveryDesc;
					v.desc = v.operateBy ? '操作人: ' + v.operateBy + " " + v.operateTime : v.operateTime;
					return v
				})
		}
		bcmOrder.value.bcmOrderGoodsList = result.ds.bcmOrderGoodsList || [];
		// bcmOrderGoodsList.value = result.ds.bcmOrderGoodsList || [];
		bcmOrderPayList.value = result.ds.bcmOrderPayList || [];
		// currentGdsList.value = result.ds.bcmOrderGoodsList || [];
		bcmOrder.value.bcmOrderGoodsList?.map(a => {
			a.pickQuantity = (a.goodsNum - (!!a.refundGoodsNum ? a.refundGoodsNum : 0)).toFixed(3);
			return a
		})
		bcmAfsOrderList.value = result.ds3;
		// console.log("result.ds3", result.ds3)
	} else {
		uni.showToast({
			duration: 3500,
			icon: 'none',
			title: '未查询到数据',
			mask: true,
		});
	}
}

onLoad((option) => {
	if (option.c_id) {
		BillId.value = option.c_id;
		billQuery(BillId.value);
	}
	showConfigModal.value = option.showModal || false;
	uni.$on('REFRESH_ORDER_DETAIL_DATA', () => {
		billQuery(BillId.value);  // 自定义的刷新页面数据的方法
	});

})
</script>
<style lang="scss">
@import "../common/common.css";

.bottom-1 {
	display: flex;
	justify-content: center;
	flex: 0 0 auto;
	// height: 70rpx;
	padding: $uni-spacing-col-sm * 2 $uni-spacing-row-sm;
	background: $uni-bg-color;
}

.footer {
	flex: 1;
	padding-bottom: 20rpx;
}

.bottom {
	display: flex;
	justify-content: flex-end;
	height: 70rpx;
	padding: $uni-spacing-col-sm*2 $uni-spacing-row-sm;
	text-align: right;
	background: $uni-bg-color;
}

.m-list-top {
	display: grid;
	padding: 8px 0;
	// border-bottom: 1px solid $uni-border-color;
	font-size: 32rpx;

	grid-template-columns: 52% 48%;
}


.popup-content {
	display: flex;
	flex-direction: column;
	width: 100%;
	padding: 0;
	background-color: #fff;

	.popup-title {
		display: flex;
		align-items: center;
		box-sizing: border-box;
		width: 100%;
		height: 100rpx;
		padding-right: 36rpx;
		padding-left: 30rpx;
		font-size: 33rpx;
		line-height: 100rpx;
		border-bottom: 1px solid #f1f1f1;
	}

	textarea {
		box-sizing: border-box;
		width: 100%;
		height: 80px;
		padding: 5px;
		margin: 5px 0;
		border: 1px solid #ccc;
		border-radius: 5px;
	}
}
</style>